import { Injectable } from '@angular/core';
import 'rxjs/add/operator/toPromise';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { JwtHelperService } from '@auth0/angular-jwt';

@Injectable()
export class AuthService {
  user: any = {
  };
  constructor(public http: HttpClient, private router: Router, private jwt: JwtHelperService) {
    // this.getUser();
  }
  login(user) {
    return new Promise((resolve, reject) => {
      this.http.post(window.API_ROOT + 'api/user_manage/login', user).toPromise().then((res: any) => {
        const data = res;
        localStorage.setItem('token', data.token);
        resolve();

      });
    });
  }
  loggedIn() {
    return !this.jwt.isTokenExpired();
  }
  logout() {
    localStorage.removeItem('token');
    sessionStorage.removeItem('user');
    this.router.navigate(['login']);
  }
  getUser() {
    return new Promise((resolve, reject) => {
      this.http.get(window.API_ROOT + 'api/login_user').toPromise().then((res: any) => {
        const data = res;
        this.user = data;
        resolve(data);
      });
    });
  }
}
